<?php

namespace im\tables;

use MongoDB\BSON\ObjectID;
use MongoDB\BSON\Persistable;
use MongoDB\BSON\UTCDateTime;

class Message implements Persistable{
    
    private $id = null,
            $from_uid = 0,
            $to_uid = 0,
            $msg = '',
            $read_time = 0,
            $create_time = 0;
    
    public function __construct($from_uid,$to_uid,$msg) {
        
        $this->id = new ObjectID();
        $this->from_uid = (int)$from_uid;
        $this->to_uid = (int)$to_uid;
        $this->msg = (string)$msg;
        $msec = floor(microtime(true) * 1000);
        $this->create_time = new UTCDateTime($msec);

    }
    
    public function __get($name) {
        if(property_exists($this, $name)){
            return $this->$name;
        }
    }
    
    public function bsonSerialize()
    {
        return [
            '_id' => $this->id,
            'from_uid' => $this->from_uid,
            'to_uid' => $this->to_uid,
            'msg' => $this->msg,
            'read_time' => $this->read_time,
            'create_time' => $this->create_time,
        ];
    }

    public function bsonUnserialize(array $data)
    {
        $this->id = $data['_id'];
        $this->from_uid = $data['from_uid'];
        $this->to_uid = $data['to_uid'];
        $this->msg = $data['msg'];
        $this->read_time = $data['read_time'];
        $this->create_time = $data['create_time'];
    }
    
}